package com.cssw.fyzb.wap.controller;

import com.alibaba.fastjson.JSON;
import com.cssw.fyzb.base.web.context.UserContext;
import com.cssw.fyzb.base.web.domain.AjaxData;
import com.cssw.fyzb.base.web.util.HttpKit;
import com.cssw.fyzb.base.web.util.PayKit;
import com.cssw.fyzb.wap.service.PayService;
import com.ydn.appserver.utils.StringUtils;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.HashMap;
import java.util.Map;

/**
 * @Author: chenchao
 * @Date: 2020/8/3 10:33
 */

@Api(description = "支付相关接口")
@RestController
@RequestMapping("/pay")
public class PayController {

    private static final Logger logger = LoggerFactory.getLogger(PayController.class);
    @Autowired
    private PayService payService;

    @ApiOperation("微信支付异步通知")
    @RequestMapping(value = "wxPayNotify", method = {RequestMethod.POST, RequestMethod.GET})
    public String wxPayNotify(HttpServletRequest request, HttpServletResponse response) throws Exception {
        String xmlMsg = HttpKit.readData(request);
        logger.debug("**************************************************");
        logger.debug("xmlMsg:" + xmlMsg);
        logger.info("wxPayNotify: " + xmlMsg);
        Map<String, String> params = PayKit.xmlToMap(xmlMsg);
        String returnCode = params.get("return_code");
        if (StringUtils.isEmpty(returnCode) || !"SUCCESS".equals(returnCode)) {
            return null;
        }
        if (payService.wxVerifyNotify(JSON.toJSONString(params))) {
            Map<String, String> xml = new HashMap(2);
            xml.put("return_code", "SUCCESS");
            xml.put("return_msg", "OK");
            String returnXml = PayKit.toXml(xml);
            return returnXml;
        }
        return null;

    }

    @ApiOperation("支付宝支付异步通知接口")
    @RequestMapping(value = "aliPayNotify", method = {RequestMethod.POST, RequestMethod.GET})
    public String aliPayNotify(HttpServletRequest request) {
        Map<String, String> params = PayKit.aliToMap(request);

        if (payService.aliVerifyNotify(JSON.toJSONString(params))) {
            return "success";
        }
        return "failure";
    }


    @ApiOperation("ada支付异步通知")
    @RequestMapping(value = "adapayNotify", method = {RequestMethod.POST, RequestMethod.GET})
    public String adapayNotify(HttpServletRequest request, HttpServletResponse response) throws Exception {

        try {
            //验签请参data
            String data = request.getParameter("data");
            //验签请参sign
            String sign = request.getParameter("sign");

            //验签
            AjaxData ajaxData = payService.verifyAdapaySign(data, sign);
            logger.info(sign + "返回数据data:"+data);
            if(ajaxData.getErrCode() == 200 && null != ajaxData.getData()){
                Map verifyData = (Map)ajaxData.getData();
                if (null == verifyData.get("checkSign") || !(Boolean)verifyData.get("checkSign")){
                    return "fail";
                }
                //验签成功逻辑
                logger.info("成功返回数据data:");
                if (payService.adapayNotify(data)) {
                    return "success";
                } else {
                    return "fail";
                }
            }else {
                //验签失败逻辑
                logger.info("验签失败逻辑data:");
                return "fail";
            }
        }catch (Exception e){
            logger.info("异步回调开始，参数，request={}");
        }

        return "success";

    }


    @ApiOperation("yespay提现异步通知")
    @RequestMapping(value = "yespayCashNotify", method = {RequestMethod.POST, RequestMethod.GET})
    public String yespayCashNotify(HttpServletRequest request, HttpServletResponse response) throws Exception {
        try {

            Map<String, String> params = PayKit.aliToMap(request);
            logger.debug(">>>>yespayCashNotify: params" + params);

            //验签
            AjaxData ajaxData = payService.verifyYespaySign(JSON.toJSONString(params));
            logger.info("返回数据data:"+ajaxData);
            if(ajaxData.getErrCode() == 200 && null != ajaxData.getData()){
                Map verifyData = (Map)ajaxData.getData();
                if (null == verifyData.get("checkSign") || !(Boolean)verifyData.get("checkSign")){
                    return "fail";
                }
                //验签成功逻辑
                logger.info("成功返回数据data:");
                if (payService.yespayCashNotify(JSON.toJSONString(params))) {
                    return "success";
                } else {
                    return "fail";
                }
            }else {
                //验签失败逻辑
                logger.info("验签失败逻辑data:");
                return "fail";
            }
        }catch (Exception e){
            logger.info("异步回调开始，参数，request={}");
        }

        return "success";

    }

    @ApiOperation("ada提现异步通知")
    @RequestMapping(value = "adapayDrawcashNotify", method = {RequestMethod.POST, RequestMethod.GET})
    public String adapayDrawcashNotify(HttpServletRequest request, HttpServletResponse response) throws Exception {

        try {
            //验签请参data
            String data = request.getParameter("data");
            //验签请参sign
            String sign = request.getParameter("sign");

            //验签
            AjaxData ajaxData = payService.verifyAdapaySign(data, sign);
            logger.info(sign + "返回drawcash数据data:"+data);
            if(ajaxData.getErrCode() == 200 && null != ajaxData.getData()){
                Map verifyData = (Map)ajaxData.getData();
                if (null == verifyData.get("checkSign") || !(Boolean)verifyData.get("checkSign")){
                    return "fail";
                }
                //验签成功逻辑
                logger.info("验签成功返回");
                if (payService.adapayDrawcashNotify(data)) {
                    return "success";
                } else {
                    return "fail";
                }
            }else {
                //验签失败逻辑
                logger.info("验签失败逻辑data:");
                return "fail";
            }
        }catch (Exception e){
            logger.info("异步回调开始，参数，request={}");
        }

        return "success";

    }

    @ApiOperation(value = "ada订单查询")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "tradeNo", value = "订单编号", paramType = "query", dataType = "string", required = true)
    })
    @GetMapping("adapayQuery")
    public AjaxData adapayQuery(String tradeNo) throws Exception {
        return payService.adapayQuery(UserContext.getUserId(), tradeNo);

    }

    @ApiOperation(value = "wx登录获取open_id")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "code", value = "微信code", paramType = "query", dataType = "string", required = true)
    })
    @GetMapping("getWxOpenId")
    public AjaxData getWxOpenId(String code) throws Exception {
        return payService.getWxOpenId(UserContext.getUserId(), code);

    }

    @ApiOperation("检查授权许可")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "code", value = "编码", paramType = "query", dataType = "string", required = true)
    })
    @GetMapping("checkLicence")
    public AjaxData checkLicence(String code) {
        return payService.checkLicence(code);
    }


    @ApiOperation("tf56支付异步通知")
    @RequestMapping(value = "tf56payPayNotify", method = {RequestMethod.POST, RequestMethod.GET})
    public String tf56payPayNotify(HttpServletRequest request, HttpServletResponse response) throws Exception {
        try {

            Map<String, String> params = PayKit.aliToMap(request);
            logger.debug(">>>>tf56payPayNotify: params" + params);

            //验签
            AjaxData ajaxData = payService.verifyYespaySign(JSON.toJSONString(params));
            logger.info("返回数据data:"+ajaxData);
            if(ajaxData.getErrCode() == 200 && null != ajaxData.getData()){
                Map verifyData = (Map)ajaxData.getData();
                if (null == verifyData.get("checkSign") || !(Boolean)verifyData.get("checkSign")){
                    return tf56payFail("验签失败");
                }
                //验签成功逻辑
                logger.info("成功返回数据data:");
                if (payService.tf56payPayNotify(JSON.toJSONString(params))) {
                    return tf56paySucc();
                } else {
                    return tf56payFail("处理失败");
                }

            }else {
                //验签失败逻辑
                logger.info("验签失败逻辑data:");
                return tf56payFail("验签失败");
            }
        }catch (Exception e){
            logger.info("异步回调开始，参数，request={}");

            return tf56payFail("验签失败");
        }


    }


    @ApiOperation("tf56签约异步通知")
    @RequestMapping(value = "tf56paySignNotify", method = {RequestMethod.POST, RequestMethod.GET})
    public String tf56paySignNotify(HttpServletRequest request, HttpServletResponse response) throws Exception {
        try {

            Map<String, String> params = PayKit.aliToMap(request);
            logger.debug(">>>>tf56paySignNotify: params" + params);

            //验签
            AjaxData ajaxData = payService.verifyYespaySign(JSON.toJSONString(params));
            logger.info("返回数据data:"+ajaxData);
            if(ajaxData.getErrCode() == 200 && null != ajaxData.getData()){
                Map verifyData = (Map)ajaxData.getData();
                if (null == verifyData.get("checkSign") || !(Boolean)verifyData.get("checkSign")){
                    return tf56payFail("验签失败");
                }
                //验签成功逻辑
                logger.info("成功返回数据data:");
                if (payService.tf56paySignNotify(JSON.toJSONString(params))) {
                    return tf56paySucc();
                } else {
                    return tf56payFail("处理失败");
                }

            }else {
                //验签失败逻辑
                logger.info("验签失败逻辑data:");
                return tf56payFail("验签失败");
            }
        }catch (Exception e){
            logger.info("异步回调开始，参数，request={}");

            return tf56payFail("验签失败");
        }


    }


    @ApiOperation("tf56退款异步通知")
    @RequestMapping(value = "tf56payRefundNotify", method = {RequestMethod.POST, RequestMethod.GET})
    public String tf56payRefundNotify(HttpServletRequest request, HttpServletResponse response) throws Exception {
        try {

            Map<String, String> params = PayKit.aliToMap(request);
            logger.debug(">>>>tf56payRefundNotify: params" + params);

            //验签
            AjaxData ajaxData = payService.verifyYespaySign(JSON.toJSONString(params));
            logger.info("返回数据data:"+ajaxData);
            if(ajaxData.getErrCode() == 200 && null != ajaxData.getData()){
                Map verifyData = (Map)ajaxData.getData();
                if (null == verifyData.get("checkSign") || !(Boolean)verifyData.get("checkSign")){
                    return tf56payFail("验签失败");
                }
                //验签成功逻辑
                logger.info("成功返回数据data:");
                if (payService.tf56payRefundNotify(JSON.toJSONString(params))) {
                    return tf56paySucc();
                } else {
                    return tf56payFail("处理失败");
                }

            }else {
                //验签失败逻辑
                logger.info("验签失败逻辑data:");
                return tf56payFail("验签失败");
            }
        }catch (Exception e){
            logger.info("异步回调开始，参数，request={}");

            return tf56payFail("验签失败");
        }


    }

    private String tf56paySucc(){
        return tf56payResult("success", "成功");
    }

    private String tf56payFail(String msg){
        return tf56payResult("error", msg);
    }

    private String tf56payResult(String result, String msg){
        Map map = new HashMap();
        map.put("result", result);
        map.put("msg", msg);
        return JSON.toJSONString(map);
    }
}
